// 查询所有动态（含回复评论）


// 得到装所有动态的小盒子
var AllDyBox = document.getElementsByClassName("AllDy")[0];

// 获得所有动态的个数
var allDyLen = 0;

// 设置存取所有动态对象的变量
var allDy = "";

// 获得动态详情的返回按钮
var detailAllDyBtn = "";

// 设置获得所有评论的数组
var commentArray = [];

// 让时间样式更清楚
function addZero(num){
  return num<10 ? '0'+num : num;
}

function switchTimeFormat (time) {
                const dateTime = new Date(time)
                const year = dateTime.getFullYear()
                const month = dateTime.getMonth() + 1
                const date = dateTime.getDate()
                const hour = dateTime.getHours()
                const minute = dateTime.getMinutes()
                const second = dateTime.getSeconds()
              return `${year}年${month}月${date}日---${addZero(hour)}:${addZero(minute)}:${addZero(second)}`;
            }
// 动态的封面(模板字符串)
function htmlDyTop(data){
    var str = '';
        str = ` <div class="everyDyBox">
              <div class="Dycover">
                <h3 class="detailDy">${data.title}</h3>
                <li class="DyCoverContent">${data.content}</li>
                <ul>
                  <li class="DyCoverName"> ${data.username}</li>
                  <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>  
                </ul>
              </div>        
            </div>
            `;
          return str;
    }
    

// 动态小卡片
function insertAllDyHtml(value){
  let dyAllContent = "";
  
  //定义的全局变量allDy,获取所有动态数据
  allDy = value;
            
  //获得所有动态的数量
  allDyLen = value.data.length;

  // 获得动态小卡片
  for(let i = 0 ; i < allDyLen ; i ++){
      dyAllContent += htmlDyTop(value.data[i]);
  }
  //插入所有动态小卡片到容器中
  AllDyBox.innerHTML = dyAllContent;

  
}


// 根据动态ID发送AJAX请求获得评论和回复
function getCommentText(dyId,userId,page){
  
  

  let data = new FormData();
  data.append("dynamicId",dyId);
  postForm(data,"getReplyById").then(value=>{
    if(value.code == 1000){
 
      
      commentStr(value.data,userId,page);
    }
    else if(value.code == 1001){
      firstComment(dyId,userId,page);
    }
  },reason=>{
    alert("发送请求失败，请检查输入格式")
  })


}

// 当没有评论时自动赋予新增评论框
function firstComment(dyId,commentOwner,page){
  let comment = `<div class="CommentsBox">
  <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
  <button class="commentBtn">新增评论</button>
  </div>
  `;
  AllDyBox.innerHTML += comment;
 if(page){
    let backAllDyBtn = document.querySelector(".backAllDy");    
        backAllDyBtn.onclick = function(){
          dyGetForm(`dynamicState/select/page/${page+1}/10`).then(value=>{
            if(value.code == 200){
                console.log(value.msg);
          
                //  传输响应结果同时
                console.log(value)

                insertAllDyPageHtml(value.data.records);

                let detailPgaeDyBtn = document.getElementsByClassName("detailDy");
    
                toDetailPageDy(detailPgaeDyBtn,value.data.records,page);
               
                if(isNight){
                  nightBtn.click();
                }
                else{
                  sunBtn.click();
                }
                
             }
             else if(value.code == 11000){
                 console.log(value.msg);
             }   
             else{
                 alert("可能后台炸了");
             }


        },
        reason=>{
            alert("AJAX发送请求失败");
        })

    
      }
       //  为发表新评论按钮绑定事件
    let newCommentBtn = document.querySelector(".commentBtn");
    newCommentBtn.onclick = function(){
    if(userInfoG){
      let ipt = document.getElementById("newCommentContent").value;
      let data = new FormData();
   
      data.append("dynamicStateId",dyId);
      data.append("replyerId",window.userInfoG.data.id);
      data.append("beReplyerId",commentOwner);
      data.append("commentsContent",ipt);
      if(ipt){
        postForm(data,"comment/insert").then(function(value){
          if(value.code == 200){
            alert("发表评论成功");
            backAllDyBtn.click();
          }
        },function(reason){
          alert("请检查格式!")
        })
      }
      else{
        alert("您暂未输入任何内容!");
      }
    }
    else{
      alert("请先登陆!");
    }
   

  } 
    }
  else{
    let backAllDyBtn = document.querySelector(".backAllDy");    
    backAllDyBtn.onclick = function(){
      dyGetForm("dynamicState/select/all").then(
        value=>{
         if(value.code == 200){
         
          
             insertAllDyHtml(value);
    
            //获取所有动态的查看消息的按钮(即按标题就可以跳转)
             let detailAllDyBtn = document.getElementsByClassName("detailDy");  
             toDetailDy(detailAllDyBtn); 

            if(isNight){
              nightBtn.click();
            }
            else{
              sunBtn.click();
            }
         }
         else if(value.code == 11000){
             console.log(value.msg);
         }   
         else{
             alert("可能后台炸了");
         }
        },
        reason=>{
            alert("AJAX请求失败")
        })
    }
     //  为发表新评论按钮绑定事件
    let newCommentBtn = document.querySelector(".commentBtn");
    newCommentBtn.onclick = function(){
      if(userInfoG){
        let ipt = document.getElementById("newCommentContent").value;
        let data = new FormData();
    
        data.append("dynamicStateId",dyId);
        data.append("replyerId",window.userInfoG.data.id);
        data.append("beReplyerId",commentOwner);
        data.append("commentsContent",ipt);
        if(ipt){
          postForm(data,"comment/insert").then(function(value){
            if(value.code == 200){
              alert("发表评论成功");
              backAllDyBtn.click();
            }
          },function(reason){
            alert("请检查格式!")
          })
        }
        else{
          alert("您暂未输入任何内容!");
        }
      }
      else{
        alert("请先登陆!");
      }
    

    } 
  
  }
         
}


// 评论的模板字符串(内含回复，删除，返回，评论功能)
function commentStr(commentArrays,commentOwner,page){
 
  let comment = `<div class="CommentsBox">
 <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
<button class="commentBtn">新增评论</button>
</div>
  `;
  AllDyBox.innerHTML += comment;
  let len = commentArrays.length;
  console.log(commentArrays);
// for遍历所有回复评论到页面种
  for(let k = 0 ; k < len ; k++){
    // 检测是不是评论
    if(commentArrays[k].replyId == 0){
      
      comment = ` 
          <div class="everyCm"> 

          
    
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}" : ${commentArrays[k].commentsContent} 
            <button id="replyBtn${commentArrays[k].id}">回复</button> 
            `;
            //为个人评论或回复增加删除按钮
          if(window.userInfoG){
            if(commentArrays[k].replyerId == window.userInfoG.data.id){
            
              comment+=`<button id="commentDelBtn${commentArrays[k].id}">删除</button>   
            `
            }
          }
          
         
            comment +=`
            </li>
         <div id = "replyBox${commentArrays[k].id}"></div>
          </div>`
          
          
          AllDyBox.innerHTML += comment;
     
    }
    else{
      // 是回复的话将这个放到回复的那个评论的盒子里面，自己再开个盒子目的是为了后面嵌套评论
      for(let j = 0 ; j < len ; j++){
        if(commentArrays[k].replyId == commentArrays[j].id){
          comment = ` 
          <div class="everyReply"> 
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}"回复<img id="beReplyerAvatar" src="${queryURL}${commentArrays[k].beReplyerPhoto}" alt="">"${commentArrays[k].beReplyerName}"说 : ${commentArrays[k].commentsContent}
            <button id="replyBtn${commentArrays[k].id}">回复</button> 
            `
          if(window.userInfoG){
            if(commentArrays[k].replyerId == window.userInfoG.data.id){
            
              comment+=`<button id="commentDelBtn${commentArrays[k].id}">删除</button>     
          `
          }
          }
         
       
          comment +=`
          </li>
       <div id = "replyBox${commentArrays[k].id}"></div>
        </div>`
        
        

          document.getElementById(`replyBox${commentArrays[j].id}`).innerHTML += comment;
        }
      }
     
    }
  }

  // 为返回按钮绑定事件(判断是否是分页状态)
  if(page){
      let backAllDyBtn = document.querySelector(".backAllDy");    
          backAllDyBtn.onclick = function(){
            dyGetForm(`dynamicState/select/page/${page+1}/10`).then(value=>{
              if(value.code == 200){
                  console.log(value.msg);
            
                  //  传输响应结果同时
                  console.log(value)

                  insertAllDyPageHtml(value.data.records);

                  let detailPgaeDyBtn = document.getElementsByClassName("detailDy");
      
                  toDetailPageDy(detailPgaeDyBtn,value.data.records,page);
                
                  if(isNight){
                    nightBtn.click();
                  }
                  else{
                    sunBtn.click();
                  }
                  
              }
              else if(value.code == 11000){
                  console.log(value.msg);
              }   
              else{
                  alert("可能后台炸了");
              }


          },
          reason=>{
              alert("AJAX发送请求失败");
          })

      
        }
        //  为发表新评论按钮绑定事件
      let newCommentBtn = document.querySelector(".commentBtn");
      newCommentBtn.onclick = function(){
        if(userInfoG){
          let ipt = document.getElementById("newCommentContent").value;
          let data = new FormData();
      
          data.append("dynamicStateId",commentArrays[0].dynamicStateId);
          data.append("replyerId",window.userInfoG.data.id);
          data.append("beReplyerId",commentOwner);
          data.append("commentsContent",ipt);
          if(ipt){
            postForm(data,"comment/insert").then(function(value){
              if(value.code == 200){
                alert("发表评论成功");
                backAllDyBtn.click();
              }
            },function(reason){
              alert("请检查格式!")
            })
          }
          else{
            alert("您暂未输入任何内容!");
          }
        }
        else{
          alert("请先登陆!");
        }
      

      } 

          // 为删除回复和添加回复按钮绑定事件
      for(let k = 0 ; k < len ; k++){
        if(window.userInfoG){
          if(commentArrays[k].replyerId == window.userInfoG.data.id){
            let itsId = commentArrays[k].id;
            let ownerId = commentArrays[k].replyerId;
            document.getElementById(`commentDelBtn${itsId}`).onclick = function(){
              if(window.userInfoG){
    
                if(ownerId == window.userInfoG.data.id){
                  let data = new FormData();
                  data.append("id",itsId)
                  postForm(data,"comment/delete").then(value=>{
                    if(value.code == 200){
                      alert("删除评论成功");
                      backAllDyBtn.click();
                    }
                  });
                }
                else{
                  alert("只能删除自己的评论或者回复哦~");
                }
    
    
    
              }
              else{
                alert("请先登陆再进行这些操作哦~")
              }
            
            
            }
  
  
  
          }

        }
        
        
        let itsId = commentArrays[k].id;
        let ownerId = commentArrays[k].replyerId;
        document.getElementById(`replyBtn${itsId}`).onclick = function(){
          if(userInfoG){
            let ipt = prompt("请输入你想要回复的内容:","");
            if(ipt){
              let data = new FormData();
      
              data.append("dynamicStateId",commentArrays[0].dynamicStateId);
              data.append("replyId",itsId);
              data.append("replyerId",window.userInfoG.data.id);
              data.append("beReplyerId",ownerId);
              data.append("commentsContent",ipt);
              postForm(data,"comment/reply").then(value=>{
                if(value.code == 200){
                  alert(value.msg);
                  backAllDyBtn.click();
                }
              },reason=>{
                alert("是否格式不对")
              })
            }
            else{
              alert("内容为空");
            }
          }
          else{
            alert("请先登陆!");
          }
        }

      }
    }
  else{
    let backAllDyBtn = document.querySelector(".backAllDy");    
    backAllDyBtn.onclick = function(){
      dyGetForm("dynamicState/select/all").then(
        value=>{
         if(value.code == 200){
         
          
             insertAllDyHtml(value);
    
            //获取所有动态的查看消息的按钮(即按标题就可以跳转)
             let detailAllDyBtn = document.getElementsByClassName("detailDy");  
             toDetailDy(detailAllDyBtn); 

             if(isNight){
              nightBtn.click();
            }
            else{
              sunBtn.click();
            }
         }
         else if(value.code == 11000){
             console.log(value.msg);
         }   
         else{
             alert("可能后台炸了");
         }
        },
        reason=>{
            alert("AJAX请求失败")
        })
    }
      //  为发表新评论按钮绑定事件
    let newCommentBtn = document.querySelector(".commentBtn");
    newCommentBtn.onclick = function(){
      if(userInfoG){
        let ipt = document.getElementById("newCommentContent").value;
        let data = new FormData();
    
        data.append("dynamicStateId",commentArrays[0].dynamicStateId);
        data.append("replyerId",window.userInfoG.data.id);
        data.append("beReplyerId",commentOwner);
        data.append("commentsContent",ipt);
        if(ipt){
          postForm(data,"comment/insert").then(function(value){
            if(value.code == 200){
              alert("发表评论成功");
              backAllDyBtn.click();
            }
          },function(reason){
            alert("请检查格式!")
          })
        }
        else{
          alert("您暂未输入任何内容!");
        }
      }
      else{
        alert("请先登陆!");
      }
    

    } 
    // 为删除回复和添加回复按钮绑定事件
    for(let k = 0 ; k < len ; k++){
    if(window.userInfoG){
      if(commentArrays[k].replyerId == window.userInfoG.data.id){
        let itsId = commentArrays[k].id;
        let ownerId = commentArrays[k].replyerId;
        document.getElementById(`commentDelBtn${itsId}`).onclick = function(){
          if(window.userInfoG){
  
            if(ownerId == window.userInfoG.data.id){
              let data = new FormData();
              data.append("id",itsId)
              postForm(data,"comment/delete").then(value=>{
                if(value.code == 200){
                  alert("删除评论成功");
                  backAllDyBtn.click();
                }
              });
            }
            else{
              alert("只能删除自己的评论或者回复哦~");
            }
  
  
  
          }
          else{
            alert("请先登陆再进行这些操作哦~")
          }
        
        
        }


      }
    }
      
     
      let itsId = commentArrays[k].id;
      let ownerId = commentArrays[k].replyerId;
      document.getElementById(`replyBtn${itsId}`).onclick = function(){
        if(userInfoG){
          let ipt = prompt("请输入你想要回复的内容:","");
          if(ipt){
            let data = new FormData();
    
            data.append("dynamicStateId",commentArrays[0].dynamicStateId);
            data.append("replyId",itsId);
            data.append("replyerId",window.userInfoG.data.id);
            data.append("beReplyerId",ownerId);
            data.append("commentsContent",ipt);
            postForm(data,"comment/reply").then(value=>{
              if(value.code == 200){
                alert(value.msg);
                backAllDyBtn.click();
              }
            },reason=>{
              alert("是否格式不对")
            })
          }
          else{
            alert("内容为空");
          }
        }
        else{
          alert("请先登陆!");
        }
      }

    }
  }
         
}


// 动态的详细内容(模板字符串)
function htmlDyDetail(data){
  var str = '';
  var imgStr ='';//所有图片
  // 是否有图片
  console.log(data)
  if(data.hasPicture){
      let imgLen = data.urls.length;
      // 将所有图片放到一个个img标签
      for(let i = 0 ; i<imgLen ; i++){
        imgStr +=`   <li class="DyImgContent">
        <img style="width: 250px;height: 250px;" src=${queryURL}${data.urls[i]} alt="">
        </li>`
      }
      
      str = ` <div class="everyDyBox">
            <div class="everyDy">
              <ul class="userDyInfo">
                <li class="userDyTitle">${data.title}</li>
              </ul>
              <ul class="userDyHeader">
                <li class="DyId">动态ID:${data.id}</li>
                <li class="userDyId">用户ID:${data.userId}</li>
                <li class="userDyname">用户名称:${data.username}</li>
                <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
              </ul>
              <ul class="userDyContent">
                <ul class="DyimgBox">
                 ${imgStr}  
                </ul>
                <li class="DyTextContent">${data.content}</li>
              </ul>
              <li class="backAllDy">
              <i class="fas fa-reply"></i> 
              </li>
            </div>
            
          </div>
          `      
          ;   
  }
  else{
      str = `   <div class="everyDyBox">
      <div class="everyDy">
        <ul class="userDyInfo">
        <li class="userDyTitle">${data.title}</li>
        </ul>
        <ul class="userDyHeader">
      
          <li class="DyId">动态ID:${data.id}</li>
          <li class="userDyId">用户ID:${data.userId}</li>
          <li class="userDyname">用户名称:${data.username}</li>
          <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
        </ul>
        <ul class="userDyContent">
          <li class="DyTextContent">${data.content}</li>
        </ul>
        <li class="backAllDy">
        <i class="fas fa-reply"></i> 
        </li>
      </div>
     
    </div>`;
  }
  return str;
}


// 给每个动态卡片绑定事件的函数
function toDetailDy(detailAllDyBtn){
  // 判断存所有动态的全局是否有数据
  if(allDy){
    //遍历动态小卡片标题按钮，绑定事件
    for(let i = 0 ; i<allDyLen ; i++){
      detailAllDyBtn[i].onclick=function(){
        // 动态大容器只展示点进去的详细动态
         
        let str = htmlDyDetail(allDy.data[i]);
      
        AllDyBox.innerHTML = str ;

        // 评论区内容和各种功能按钮
        
        getCommentText(allDy.data[i].id,allDy.data[i].userId);
        // 获取进入当前详细动态里面的回退按钮

        
      }  
    }
  }
  else{
    alert("动态未获取");
  }
}

//检测是不是第一次点击查询所有
//是的话自动开启分页，增加分页按钮
var times = 0;
// 点击查看所有动态
queryDyAllBtn.onclick = function(){
  // 查询所有动态的页面出现,个人空间消失
    // 发送请求获得数据
    dyGetForm("dynamicState/select/all").then(
        value=>{
         if(value.code == 200){
            console.log(value.msg);
      
           allDyLen = value.data.length;

          
            //  传输响应结果同时
            insertAllDyHtml(value);

             //获取所有动态的查看消息的按钮(即按标题就可以跳转)
             let detailAllDyBtn = document.getElementsByClassName("detailDy");
            // 为可以跳转到详细动态的按钮绑定事件的函数
             toDetailDy(detailAllDyBtn);

            if(times == 0){
              displayPage(value.data.length);
              times++;
            }
            else{
              let pageBtn = document.querySelectorAll(".pageBtn");
              for(let j = 0 ; j < parseInt(value.data.length/10)+1 ;j++){
                pageBtn[j].setAttribute("class","pageBtn nomal");
              }
            }
            
            if(isNight){
              nightBtn.click();
            }
            else{
              sunBtn.click();
            }
         }
         else if(value.code == 11000){
             console.log(value.msg);
         }   
         else{
             alert("可能后台炸了");
         }
        },
        reason=>{
            alert("AJAX请求失败")
        }
    )
}